package com.gift.recommendation.modules.user.biz;

import com.gift.recommendation.Base.PageData;
import com.gift.recommendation.modules.admin.service.ExpressCompanyService;
import com.gift.recommendation.modules.login.dto.EmailEntityExt;
import com.gift.recommendation.modules.user.dao.entity.AddressEntity;
import com.gift.recommendation.modules.user.dao.entity.CancelOrderEntity;
import com.gift.recommendation.modules.user.service.AddressService;
import com.gift.recommendation.modules.user.service.CancelOrderService;
import com.gift.recommendation.util.PageTransUtil;
import com.gift.recommendation.modules.admin.dao.entity.GoodsEntity;
import com.gift.recommendation.modules.admin.service.GoodsService;
import com.gift.recommendation.modules.user.dao.entity.OrderEntity;
import com.gift.recommendation.modules.user.dto.*;
import com.gift.recommendation.modules.user.service.OrderService;
import com.gift.recommendation.util.KdApiSearch;
import com.gift.recommendation.util.SendEmail;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.annotation.Order;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2023/2/17
 */
@Service
public class OrderBiz {

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ExpressCompanyService expressCompanyService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private CancelOrderService cancelOrderService;

    @Autowired
    private SendEmail sendEmail;

    @Autowired
    private KdApiSearch kdApiSearch;

    /**
     * 用户下订单
     * @param req
     */
    @Transactional
    public void placeOrder(OrderReq req) {
        checkStock(req.getGoodsUuid());
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderUuid(UUID.randomUUID().toString());
        orderEntity.setOrderStatus(1);
        orderEntity.setGoodsUuid(req.getGoodsUuid());
        orderEntity.setUserUuid(req.getUserUuid());
        Example exampleOrder = new Example(AddressEntity.class);
        Example.Criteria criteriaOrder = exampleOrder.createCriteria();
        criteriaOrder.andEqualTo("userUuid",req.getUserUuid());
        criteriaOrder.andEqualTo("uuid",req.getAddressUuid());
        AddressEntity addressEntity = addressService.selectByExample(exampleOrder).get(0);
        orderEntity.setAddress(addressEntity.getArea() + " " + addressEntity.getDetail() + " (" + addressEntity.getName() + " 收) " +
                addressEntity.getTel());
        orderEntity.setMsg(req.getMsg());
        orderEntity.setMsgType(req.getMsgType());
        orderEntity.setCount(req.getCount());
        orderEntity.setUnitPrice(req.getPrice());
        orderEntity.setEmail(req.getEmail());
        goodsService.updateStock(req);
        orderService.insertSelective(orderEntity);
    }

    /**
     * 检查商品库存
     * @param goodsUuid
     */
    private void checkStock(String goodsUuid) {
        Example example = new Example(GoodsEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid",goodsUuid);
        GoodsEntity goodsEntity = goodsService.selectOneByExample(example);
        if (goodsEntity.getStock() == 0){
            throw new RuntimeException("商品已售罄");
        }
    }

    /**
     * 查看商品列表
     * @param req
     * @return
     */
    public PageData<OrderRsp> listOrderPage(OrderListReq req) {
        com.github.pagehelper.Page<OrderRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        orderService.selectList(req);
        return PageTransUtil.createPageList(page, OrderRsp.class);
    }

    /**
     * 商家发货
     * @param req
     */
    public void deliver(OrderSendReq req) {
        OrderEntity order = new OrderEntity();
        order.setExpressId(req.getExpressId());
        order.setExpressCompany(req.getExpressCompany());
        order.setOrderStatus(2);
        order.setId(req.getId());
        orderService.updateByPrimaryKeySelective(order);
        Example example = new Example(GoodsEntity.class);
        Example.Criteria criteria = example.createCriteria();
        OrderEntity orderEntity = orderService.selectByPrimaryKey(req.getId());
        criteria.andEqualTo("uuid",orderEntity.getGoodsUuid());
        GoodsEntity goods = goodsService.selectByExample(example).get(0);
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setStock(goods.getStock() - orderEntity.getCount());
        goodsService.updateByExampleSelective(goodsEntity,example);
    }

    /**
     * 根据uuid获取快递信息
     * @param req
     * @return
     */
    @Transactional
    public OrderExpressRsp showExpress(OrderMessageReq req) {
        Example example = new Example(OrderEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",req.getId());
        criteria.andEqualTo("userUuid",req.getUserUuid());
        OrderEntity order = orderService.selectByExample(example).get(0);
        if (order.getOrderStatus() != 3) {
            try {
                String logistic = kdApiSearch.orderOnlineByJson(order.getExpressCompany(),order.getExpressId()).toJSONString();
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setLogistics(logistic);
                orderService.updateByExampleSelective(orderEntity,example);
            }catch (Exception e){
                throw new RuntimeException("查询快递信息失败");
            }
        }
        return orderService.selectExpress(req);
    }

    /**
     * 确认收货
     * @param req
     */
    public void confirmOrder(OrderMessageReq req) {
        Example example = new Example(OrderEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",req.getId());
        criteria.andEqualTo("userUuid",req.getUserUuid());
        OrderEntity order = new OrderEntity();
        order.setOrderStatus(3);
        orderService.updateByExampleSelective(order,example);

        OrderEntity tmp = orderService.selectByExample(example).get(0);
        if (tmp.getMsgType() == 1) {
            EmailEntityExt emailEntityExt = new EmailEntityExt();
            emailEntityExt.setEmail(tmp.getEmail());
            emailEntityExt.setData(tmp.getMsg());
            sendEmail.sendEmails(emailEntityExt);
        }
    }

    /**
     * 获取快递公司
     * @return
     */
    public List<ExpressCompanyRsp> expressCompany() {
        List<ExpressCompanyRsp> list = expressCompanyService.selectAll().stream().map(s -> {
            ExpressCompanyRsp expressCompanyRsp = new ExpressCompanyRsp();
            BeanUtils.copyProperties(s,expressCompanyRsp);
            return expressCompanyRsp;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 库存校验
     * @param req
     * @return
     */
    public CheckStorageRsp checkStorage(CheckStorageReq req) {
        Example exampleGood = new Example(GoodsEntity.class);
        Example.Criteria criteriaGood = exampleGood.createCriteria();
        criteriaGood.andEqualTo("uuid",req.getGoodsUuid());
        GoodsEntity goods = goodsService.selectByExample(exampleGood).get(0);
        CheckStorageRsp checkStorageRsp = new CheckStorageRsp();
        if (goods.getReserveStock() >= req.getCount()) {
            checkStorageRsp.setStatus(1);
        } else {
            checkStorageRsp.setStatus(2);
        }
        return checkStorageRsp;
    }

    /**
     * 撤回订单
     * @param req
     */
    public void cancelOrder(CancelOrderReq req) {
        OrderEntity order = orderService.selectByPrimaryKey(req.getId());
        Example example = new Example(GoodsEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid",order.getGoodsUuid());
        GoodsEntity good = goodsService.selectByExample(example).get(0);
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setReserveStock(good.getReserveStock()+order.getCount());
        goodsEntity.setId(good.getId());
        goodsService.updateByPrimaryKeySelective(goodsEntity);
        //删除订单信息
        OrderEntity updateOrder = new OrderEntity();
        updateOrder.setOrderStatus(4);
        updateOrder.setId(order.getId());
        orderService.updateByPrimaryKeySelective(updateOrder);

        //插入取消表
        CancelOrderEntity cancelOrderEntity = new CancelOrderEntity();
        cancelOrderEntity.setOrderUuid(order.getOrderUuid());
        cancelOrderEntity.setReason(req.getType());
        cancelOrderEntity.setMsg(req.getMsg());
        cancelOrderService.insertSelective(cancelOrderEntity);
    }

    /**
     *
     * @param req
     * @return
     */
    public ShowCancelOrderRsp showCancelOrder(ShowCancelOrderReq req) {
        Example example = new Example(CancelOrderEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderUuid",req.getOrderUuid());
        CancelOrderEntity cancelOrderEntity = cancelOrderService.selectByExample(example).get(0);
        ShowCancelOrderRsp result = new ShowCancelOrderRsp();
        result.setType(cancelOrderEntity.getReason());
        result.setMsg(cancelOrderEntity.getMsg());
        return result;
    }
}
